<?php

namespace app\common\keloop;

use GuzzleHttp\Client;

class Base
{
    private $app_key = 'dadab3ab08bc11e7ecf';

    private $app_secret = '82a796ce54741e245a9d250bd81daf21';

    private $v = "1.0";

    private $format = "json";

    private $source_id = '647891852';
//    private $source_id = '609800';


    public function __construct($app_key = null, $app_secret = null ,$source_id = null)
    {
        if($app_key && $app_secret){
            $this->app_key = $app_key;
            $this->app_secret = $app_secret;
        }
        if($source_id){
            $this->source_id = $source_id;
        }
    }

    private function getBaseUrl()
    {
        if ($this->source_id == '647891852') {
            return 'http://newopen.qa.imdada.cn';
        }
        return 'http://newopen.imdada.cn';
    }

    public function makeRequest($path, $data) 
    {
        $body = empty($data) ? '' : json_encode($data, JSON_UNESCAPED_UNICODE);
        $reqParams = $this->bulidRequestParams($body);
        $resp = json_decode((new Client)->post($this->getBaseUrl().$path, ['json' => $reqParams])->getBody(), true);
        return $resp;
    }

    public function __get($string)
    {
        $class_name = __NAMESPACE__ . '\\'.ucfirst($string);
        return new $class_name($this);
    }

    /**
     * 构建请求参数
     */
    private function bulidRequestParams($body) 
    {
        $requestParams['app_key'] = $this->app_key;
        $requestParams['body'] = $body;
        $requestParams['format'] = 'json';
        $requestParams['v'] = $this->v;
        $requestParams['source_id'] = $this->source_id;
        $requestParams['timestamp'] = time();
        $requestParams['signature'] = $this->sign($requestParams);
        return $requestParams;
    }


    /**
     * 签名
     */
    private function sign($data) 
    {
        // 1.升序排序
        ksort($data);

        // 2.字符串拼接
        $args = "";
        foreach ($data as $key => $value) {
            $args .= $key . $value;
        }
        $args = $this->app_secret . $args . $this->app_secret;

        // 3.MD5签名,转为大写
        $sign = strtoupper(md5($args));

        return $sign;
    }

    /**
     * @param $code
     * @return string
     * 达达状态码，需要添加其它状态码自行添加
     * https://newopen.imdada.cn/#/development/file/code
     */
    public static function getDaDaCode($code){
        switch ($code){
            case 2155:
                $res = '总平台配送订单余额不足，请联系充值';
                break;
            case 2004:
                $res = '无效的门店编号,请联系管理人员查看';
                break;
            case 2002:
                $res = '没有绑定正式商户,请联系管理人员配置';
                break;
            default:
                $res = '操作失败';
                break;
        }
        return $res;
    }
}